package com.huluobo.a2201mvvm_imdemo.shop;


import android.content.Intent;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huluobo.a2201mvvm_imdemo.R;
import com.huluobo.a2201mvvm_imdemo.adapter.ShopAdapter;
import com.huluobo.a2201mvvm_imdemo.databinding.FragmentShopBinding;
import com.huluobo.a2201mvvm_imdemo.mvvm.BaseMVVMFragment;

import java.util.ArrayList;
import java.util.List;

public class ShopFragment extends BaseMVVMFragment<FragmentShopBinding, ShopViewModel> {

    private ShopAdapter shopAdapter;
    private List<GoodsBeanResult.GoodsBean> goodsBeanList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shop;
    }

    @Override
    protected void initData() {
        viewModel.getGoodsList(0, 1, 10);

        viewModel.success.observe(this, goodsBeanResult -> {
            if (goodsBeanResult.getCode() == 200) {
                goodsBeanList.clear();
                goodsBeanList.addAll(goodsBeanResult.getData());
                shopAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(goodsBeanResult.getMessage());
            }
        });

        viewModel.failed.observe(this, s -> {
            Log.i("TagA", "获取商品列表失败:" + s);
        });
    }

    @Override
    protected void initView() {
        dataBinding.shopRv.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        shopAdapter = new ShopAdapter(goodsBeanList);
        dataBinding.shopRv.setAdapter(shopAdapter);

        shopAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(requireContext(), DetailActivity.class);
            intent.putExtra("goodsId", goodsBeanList.get(position).getId());
            startActivity(intent);
        });
    }

    @Override
    protected Class<ShopViewModel> getViewModel() {
        return ShopViewModel.class;
    }
}